package com.xue.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.xue.dao.IngredientRepository;
import com.xue.pojo.Ingredient;

@RestController
@RequestMapping(path = "/api/ingredients", produces = "application/json")
@CrossOrigin(origins = "http://localhost:8080")
public class IngredientController {

//	private List<Ingredient> list;
//
//	public IngredientController() {
//		list = new ArrayList<>();
//		Ingredient ingredient = new Ingredient("id1", "name1", Ingredient.Type.CHEESE);
//		list.add(ingredient);
//	}
//
//	@GetMapping
//	public Iterable<Ingredient> allIngredients() {
//		return list;
//	}
//
//	@PostMapping
//	@ResponseStatus(HttpStatus.CREATED)
//	public Ingredient saveIngredient(@RequestBody Ingredient ingredient) {
//		list.add(ingredient);
//		return ingredient;
//	}
//
//	@DeleteMapping("/{id}")
//	@ResponseStatus(HttpStatus.NO_CONTENT)
//	public void deleteIngredient(@PathVariable("id") String ingredientId) {
//		var it = list.iterator();
//		while (it.hasNext()) {
//			var vo = it.next();
//			if (vo.getId().equals(ingredientId)) {
//				it.remove();
//			}
//		}
//	}

	private IngredientRepository repo;

	@Autowired
	public IngredientController(IngredientRepository repo) {
		this.repo = repo;
	}

	@GetMapping
	public Iterable<Ingredient> allIngredients() {
		return repo.findAll();
	}

	@PostMapping
	@ResponseStatus(HttpStatus.CREATED)
	public Ingredient saveIngredient(@RequestBody Ingredient ingredient) {
		return repo.save(ingredient);
	}

	@DeleteMapping("/{id}")
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void deleteIngredient(@PathVariable("id") String ingredientId) {
		repo.deleteById(ingredientId);
	}

}